/**
 *
 */
package co.fitstart.weapp.api.web.controller.content;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.content.Activity;
import co.fitstart.weapp.api.service.ContentService;

/**
 * @author downpour
 *
 */
@RestController
@RequestMapping("/activities")
public class ActivityApiController {

    @Autowired
    private ContentService contentService;
    
    private Logger logger = LoggerFactory.getLogger(ActivityApiController.class);
    
    /**
     * 
     * @param perPage
     * @return
     */
    @RequestMapping(path = "", method = RequestMethod.GET, params="perPage")
    public HttpResult list(@RequestParam("perPage") int perPage) {
        HttpResult result = new HttpResult();
        
        try {
            
            List<Activity> activities = contentService.listActivity(perPage);
            result.success().data("activities", activities);
            
        } catch (Exception e) {
            result.fail("500").message("获取数据失败");
            logger.error("list - ", e);
        }

        return result;
    }

    /**
     * List activity
     *
     * @param keyword
     * @param page
     * @return
     */
    @RequestMapping("")
    public HttpResult list(@RequestParam(value = "q", required = false) String keyword, Page page) {

        HttpResult result = new HttpResult();

        int totals = contentService.countActivity(keyword);
        
        if(totals > 0) {
            List<Activity> activities = contentService.listActivity(keyword, page.with(totals));

            result.success().data("page", page)
                            .data("activities", activities);
            if(StringUtils.isNoneBlank(keyword)) {
                result.data("q", keyword);
            }
        }
        
        return result;
    }

}
